<template>
  <div class="app-container">
    <el-form class="searchForm" :inline="true" size="mini" ref="searchForm" :model="searchForm">
      <el-form-item label="信号量名称">
        <el-input v-model="searchForm.name" clearable placeholder="请输入信号量名称" />
      </el-form-item>
      <el-form-item label="信号量编码">
        <el-input v-model.trim="searchForm.code" maxlength="8" oninput="value=value.replace(/[\W]/g,'')" clearable
          placeholder="请输入信号量编码" />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
          <el-option v-for="item in enums.SEMAPHORE_TYPE" :key="item.code" :label="item.label" :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备分类">
        <el-select v-model="searchForm.equipClassify" placeholder="请选择设备分类" disabled>
          <el-option v-for="item in enums.EQUIP_CLASSIFY" :key="item.code" :label="item.label" :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="doSearch">搜索</el-button>
        <el-button type="default" size="mini" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="searchs-content">
      <el-button v-permission="['system:semaphore:add']" type="primary" size="mini" plain icon="el-icon-plus"
        @click="addDialog">新增</el-button>
    </div>
    <Table :tableHeader="tableHeader" :tableData="tableData" :tableLoading="listLoading">
      <template slot="action" slot-scope="scope">
        <el-button type="primary" size="mini" @click="addDialog(scope.row)"
          v-permission="['system:semaphore:edit']">编辑</el-button>
        <el-button type="danger" size="mini" @click="handleDelete(scope.row)"
          v-permission="['system:semaphore:delete']">删除</el-button>
      </template>
    </Table>
    <pagination v-if="total > 0" :total="total" :page.sync="searchForm.pageNum" :limit.sync="searchForm.pageSize"
      @pagination="fetchData" />

    <!-- 弹框 -->
    <Dialog :visible="visible" width="32%" :loading="dialogBtnLoading" :title="dialogTitle" @confirmDialog="confirmDialog"
      @cancelDialog="cancelDialog">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px" :rules="dialogRules" size="small">
        <el-form-item label="信号量名称" prop="name">
          <el-input class="ipt" placeholder="请输入信号量名称" v-model="dialogForm.name" clearable />
        </el-form-item>
        <el-form-item label="信号量编码" prop="code">
          <el-input :disabled="dialogForm.id ? true : false" class="ipt" placeholder="请输入信号量编码" v-model="dialogForm.code" clearable />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select class="ipt" v-model="dialogForm.type" placeholder="请选择类型" clearable>
            <el-option v-for="item in enums.SEMAPHORE_TYPE" :key="item.code" :label="item.label" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备分类" prop="equipClassify">
          <el-select class="ipt" v-model="dialogForm.equipClassify" placeholder="请选择设备分类" disabled>
            <el-option v-for="item in enums.EQUIP_CLASSIFY" :key="item.code" :label="item.label" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import { semaphore } from "@/api/manage";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";
import { mapGetters } from "vuex";

export default {
  components: { Pagination, Table, Dialog },
  data() {
    var validateCode = (rule, value, callback) => {
      let re = /^[0-9a-zA-Z]*$/g; //判断字符串是否为数字和字母组合
      if (value === "") {
        callback(new Error("请输入信号量编码"));
      } else if (value.length > 8) {
        callback(new Error("信号量编码不能超过8位"));
      } else if (!re.test(this.dialogForm.code)) {
        callback(new Error("请输入数字或字母组合"));
      } else {
        callback();
      }
    };
    return {
      listLoading: true,
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 15,
        code: "",
        equipClassify: "",
        name: "",
        type: "",
      },

      tableHeader: [
        {
          type: "index",
          label: "序号",
          width: "60",
          fixed: true,
        },
        {
          label: "code",
          prop: "code",
        },
        {
          label: "名称",
          prop: "name",
        },
        {
          label: "类型",
          prop: "type",
          formatter: (item) => {
            let classify = this.enums.SEMAPHORE_TYPE.find((p) => {
              return p.code == item.type;
            });
            return classify.label;
          },
        },
        {
          label: "设备分类",
          prop: "equipClassify",
          formatter: (item) => {
            let classify = this.enums.EQUIP_CLASSIFY.find((p) => {
              return p.code == item.equipClassify;
            });
            return classify.label;
          },
        },
        {
          label: "创建人",
          prop: "createBy",
        },
        {
          label: "创建时间",
          prop: "createTime",
        },
        { slot: "action", label: "操作", width: "180" },
      ],
      tableData: [],
      visible: false, //弹框标识
      dialogForm: {
        code: "",
        equipClassify: "",
        name: "",
        type: "",
      },
      dialogRules: {
        code: [{ required: true, trigger: "blur", validator: validateCode }],
        name: [
          { required: true, message: "请输入信号量名称", trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        equipClassify: [
          { required: true, message: "请选择设备分类", trigger: "change" },
        ],
      },
      dialogTitle: "",

      dialogBtnLoading: false,

      currentRow: {},
    };
  },

  computed: {
        ...mapGetters(["enums", "equipTypeCode"]),
  },
  watch:{
    equipTypeCode:{
      handler(val){
        this.searchForm.equipClassify = val;
      },
      immediate:true,
    }
  },
  
  async created() {
    this.fetchData();
  },
  methods: {
    fetchData(val) {
      this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
      this.listLoading = true;
      this.tableData = [];
      this.total = 0;
      semaphore("/list", "post", { ...removeNullUndefined(this.searchForm) }, 1)
        .then((res) => {
          this.tableData = res.data;
          this.total = +res.total;

          this.searchForm.pageNum = +res.pageNum;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },

    // 弹框取消
    cancelDialog() {
      this.visible = false;
      this.clearData();
      this.resetDialogForm("dialogForm");
    },
    clearData() {
      this.dialogForm = {
        code: "",
        equipClassify: "",
        name: "",
        type: "",
      };
    },
    // 弹框确认
    confirmDialog() {
      this.submitDialogForm("dialogForm");
    },
    // 新增
    async addDialog(row) {
      this.visible = true;

      if (row.id) {
        this.dialogTitle = "编辑";
        this.currentRow = { ...row };
        let { id, code, equipClassify, name, type } = row;
        this.dialogForm = {
          id,
          code,
          equipClassify,
          name,
          type,
        };
      } else {
        this.dialogTitle = "新增";
        this.currentRow = {};
        this.dialogForm = {
          code: "",
          equipClassify: this.equipTypeCode,
          name: "",
          type: "",
        };
      }
    },
    handleDelete(row) {
      handleConfirm("删除后不可恢复，确定继续？", "warning", "提示")
        .then((res) => {
          this.doDelete(row);
        })
        .catch((err) => { });
    },
    doDelete(row) {
      semaphore(`/delete/${row.code}`, "DELETE").then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.fetchData();
        }
      });
    },

    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let msg = this.currentRow.id ? "编辑" : "新增";
          handleConfirm(`确定要${msg}吗？`, "warning", "提示")
            .then((res) => {
              this.doAdd();
            })
            .catch((err) => { });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetDialogForm(formName) {
      this.$refs[formName].resetFields();
    },

    resetSearch() {
      this.searchForm = {
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        code: "",
        equipClassify: this.equipTypeCode,
        name: "",
        type: "",
      };
    },
    doSearch() {
      this.searchForm.pageNum = 1;
      this.fetchData();
    },

    doAdd() {
      this.dialogBtnLoading = true;
      let url = this.currentRow.id ? `/update` : "/insert";
      this.dialogForm.id = this.currentRow.id;
      semaphore(url, "post", this.dialogForm, 1)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.visible = false;
            this.fetchData();
          }
        })
        .finally(() => {
          this.dialogBtnLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.ipt {
  width: 94%;
}
.searchForm {
  padding-left: 8px;
    .el-form-item {
        margin-bottom: 8px;
    }
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000000;
}
</style>
